package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.chapter.ChapterVo;
import com.atguigu.eduservice.entity.chapter.VideVo;
import com.atguigu.eduservice.mapper.EduChapterMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-02-09
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    EduVideoService eduVideoService;


    //根据课程id获取所有的章节小节
    @Override
    public List<ChapterVo> getChapterVideoById(String courseId) {
        QueryWrapper<EduChapter> qw = new QueryWrapper<>();
        qw.eq("course_id", courseId);
        List<EduChapter> list = this.list(qw);
        List<ChapterVo> result = new ArrayList<>();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                EduChapter eduChapter = list.get(i);
                ChapterVo chapterVo = new ChapterVo();
                BeanUtils.copyProperties(eduChapter, chapterVo);
                String chapterId = eduChapter.getId();
                QueryWrapper<EduVideo> q2 = new QueryWrapper<>();
                q2.eq("chapter_id", chapterId);
                List<VideVo> children = new ArrayList<>();
                List<EduVideo> list2 = eduVideoService.list(q2);
                if (list2 != null) {
                    for (int j = 0; j < list2.size(); j++) {
                        EduVideo video = list2.get(j);
                        VideVo videVo = new VideVo();
                        BeanUtils.copyProperties(video, videVo);
                        children.add(videVo);
                    }
                }
                chapterVo.setChildren(children);
                result.add(chapterVo);
            }
        }
        return result;
    }

    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id", chapterId);
        int count = eduVideoService.count(queryWrapper);
        if (count == 0) this.removeById(chapterId);
        return count > 0 ? false : true;
    }

    @Override
    public void removeByCourseId(String id) {//根据课程id删除章节
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id);
        baseMapper.delete(queryWrapper);
    }
}
